import cherrypy
from django.utils import simplejson

from google.appengine.ext.db import Error, Key, Query

from app.controllers.post import PostController
from app.controllers.department import DepartmentController
from app.controllers.employee import EmployeeController
from app.controllers.payroll import PayrollController
from app.dutil import toClass

from app.models import PayDetails, PayBenefit, Benefit

import types

class EmployeeHandler(object):
	@cherrypy.expose
	def index(self):
		pass	
	
	@cherrypy.expose
	def benefits(self, id):
		dPayBenefits = PayrollController.getEmployeeBenefits(int(id))
		return simplejson.dumps(dPayBenefits)
		
	@cherrypy.expose
	def payroll(self, *args, **kwargs):
		
		oPayroll = toClass(kwargs)
		rsBenefits = Benefit.get_by_id([int(sBenefits) for sBenefits in oPayroll.benefits])
			
		queryPayBenefits = Query(PayBenefit)
		queryPayBenefits.filter('benefit in',[rBenefit.key() for rBenefit in rsBenefits])
		queryPayBenefits.filter('pay_details =',PayDetails.get_by_id(int(oPayroll.id)).key())
		queryPayBenefits.order('-__key__')
		rsPayDetails = queryPayBenefits.fetch(1000)
		
		try:
			for rPayDetail in rsPayDetails: 
				rPayDetail.delete()	
			return simplejson.dumps(dict([('msg','Succeded')]))
		except db.TransactionFailedError:
			return simplejson.dumps(dict([('msg','Failure')]))
	
	@cherrypy.expose	
	def employees(self, *args, **kwargs):
		columns = ['idno','surname','othernames','post','active']
		rsEmployees = EmployeeController.getEmployees()
		dEmployees = dict([('page',1), ('rows',[rEmployee.toCells(columns) for rEmployee in rsEmployees])])
		dEmployees.update(total=len(dEmployees['rows']))
		return simplejson.dumps(dEmployees)
	
	@cherrypy.expose
	def vemployee(self,id=None):
		try:
			rsPosts = PostController.getPosts()
			if id is not None:
				rsEmployee = EmployeeController.getEmployee(int(id))
				dEmployee = rsEmployee.toRow()
				dEmployee.update([('posts',[rPost.toRows(['name']) for rPost in rsPosts])])
				return simplejson.dumps(dEmployee)
			else:
				return simplejson.dumps([rPost.toRows() for rPost in rsPosts])
		except TypeError:
			return None
			
	@cherrypy.expose
	def uemployee(self, *args, **kwargs):
		if kwargs:
			brs = EmployeeController.updateEmployee(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def aemployee(self, *args, **kwargs):
		if kwargs:
			brs = EmployeeController.addEmployee(toClass(kwargs))
		else: brs = False
			
		return simplejson.dumps(dict([('success',brs)]))
	
	@cherrypy.expose
	def demployee(self, id=None):
		if id is not None:
			brs = EmployeeController.deleteEmployee(id)
		else: brs = False
		
		return simplejson.dumps(dict([('success',brs)]))